<?php $this->headLink()->appendStylesheet($this->websiteUrl . 'system/css/jquery-ui-theme/jquery-ui-1.8.5.custom.css');?>
<?php $this->headScript()->appendFile($this->websiteUrl . 'system/js/php.js'); ?>
<?php $this->headScript()->appendFile(RCMS_Object_QuickConfig_QuickConfig::G_JQUI_HOSTED_URL); ?>
<?php $this->headScript()->captureStart() ?>
	!$.ui && document.write(unescape('%3Cscript src="<?php echo $this->websiteUrl;?>system/js/jquery/jquery-ui.js"%3E%3C/script%3E'))
<?php $this->headScript()->captureEnd() ?>
<?php $this->headScript()->appendFile($this->websiteUrl . 'system/js/quote/quote.js'); ?>
<?php $this->headScript()->appendFile($this->websiteUrl . 'system/js/shoppingforcontent/shoppingforcontent.js'); ?>
<?php //if (false !== @file_get_contents($this->websiteUrl . 'system/js/jquery/i18n/jquery.ui.datepicker-'.$this->lang.'.js')) { $this->headScript()->appendFile($this->websiteUrl.'system/js/jquery/i18n/jquery.ui.datepicker-'.$this->lang.'.js'); }; ?>
<script>

function loadStates(country) {
    var str = '';

    switch (country) {
        case 'US':
            var states = <?php echo json_encode(RCMS_Object_QuickConfig_QuickConfig::$stateListUSA); ?> ;
            break;
        case 'CA':
            var states = <?php echo json_encode(RCMS_Object_QuickConfig_QuickConfig::$stateListCanada); ?> ;
            break;
        default:
            var states = {}
            break;
    }
    for (var state in states){
        str += '<option value="'+state+'">'+states[state]+'</option>'
    }
    return str;
}

    $(function(){
		$('#ajaxmsg').css({position: 'fixed'});
        $('#qupdDate').datepicker({ dateFormat: '<?php echo $this->datepickerFormat; ?>', changeMonth: true, changeYear: true, yearRange: 'c-02:c+10'})
        $('#qupdValidUntilDate').datepicker({ dateFormat: '<?php echo $this->datepickerFormat; ?>', changeMonth: true, changeYear: true, yearRange: 'c-02:c+10'})

        $("#cart-quote-country").find("option[value='<?php echo $this->additionalUserData['country'];?>']").attr('selected','selected');
        <?php if (!empty($this->additionalUserData['state']) && $this->additionalUserData['state']!='null' )   :?>
        $("#cart-quote-state").html(loadStates($("#cart-quote-country").val()))
                .find("option[value='<?php echo $this->additionalUserData['state'];?>']").attr('selected','selected');
        <?php else: ?>
		$("#cart-quote-state").attr('disabled', true);
        <?php endif; ?>
            
        $("#shipping-country").find("option[value='<?php echo $this->shippingData['country']?>']").attr('selected','selected');
        <?php if (!empty($this->shippingData['state']) && $this->shippingData['state']!='null' )   :?>
        $("#shipping-state").html(loadStates($("#shipping-country").val()))
                .find("option[value='<?php echo $this->shippingData['state']?>']").attr('selected','selected');
        <?php endif; ?>
        if (!$('#same-data-for-shipping').attr('checked')) $('#shipping-data').show()

        $('#same-data-for-shipping').change(function(){
            if (!$(this).attr('checked')) {
                $('#shipping-data').find(':input').each(function(){
                    $(this).removeAttr('disabled');
                });
            } else {
                $('#shipping-data').find(':input').each(function(){
                   $(this).attr('disabled', true);
                });
            }
        });

        $("select[id$=country]").change(function(){
            var stateField = $(this).closest('div').find('select[id$=state]:first')

            if ($(this).val() == 'US' || $(this).val() == 'CA'){
                  stateField.removeAttr('disabled')
                  stateField.html(loadStates($(this).val()))
            } else {
                  stateField.attr('disabled',true)
                  stateField.html('')
            }
        });

        $('input.recountTotal').bind('keyup', function(){
                if ($(this).val() == '') {
					$(this).val('0');
				}
				reCountTotalPrice();
            }).bind('keypress', function(event){
                var key = (typeof event.charCode == undefined ? event.keyCode : event.charCode);
                if (event.ctrlKey || event.altKey || key < 32) return true;
                key = String.fromCharCode(key);
				return ( !isNaN(key) || key == '.' );
            }).bind('blur', function(){ 
				var value = parseFloat($(this).val()); 
				$(this).val(value.toFixed(2)); 
			});
		$('#discount-tax-rate').change(function(){
			reCountTotalPrice();
		}).data('currentRule', <?php echo json_encode($this->currentTaxRule); ?>);
		
		$('#quote-disclaimer').focus( function(){
				var value = trim($(this).val());
				if (value == '{%Disclaimer%}:') {
					$(this).before('<label>'+value+'</label>')
					$(this).val('');
					
				}
			}).blur( function(){
				if (trim($(this).val()) =='') {
					$(this).val('{%Disclaimer%}:');
					$(this).prev('label').remove();
				}
			});
		$('#address-list-search').blur(function(){
				if ($(this).val()!='{%Start typing id, name or email to search among addresses%}')
					$(this).val('{%Start typing id, name or email to search among addresses%}').css({color: '#ddd'});
				$('#address-list-status').find('span').text('').end().find('img').hide();
			})
			.focus(function(){
				if ($(this).val() == '{%Start typing id, name or email to search among addresses%}')
					$(this).val('').css({color: '#000'});
			})
			.autocomplete({
				source: function(request, response){
					var term = request.term;
					if (term in ajaxCache){
						response(ajaxCache[term]);
						return
					}
					$('#address-list-status').find('span').text('').end().find('img').show();
					lastXhr = $.getJSON('<?php echo $this->websiteUrl;?>sys/backend_quote/getquotedata/', request, function(data, status, xhr){
						$('#address-list-status').find('img').hide();
						if (!data.length){
							$('#address-list-status').find('span').text('{%No matches%}');
						} else {
							$('#address-list-status').find('span').text(data.length+' {%matches%}');
						}
						ajaxCache[term] = data;
						if ( xhr === lastXhr ) {
							response(data);
						}
					});
				},
				minLength: 3,
				select: function(event, ui){
					try {
						$('#cart-quote-name').val(ui.item.billing_name);
						$('#cart-quote-company').val(ui.item.billing_company);
						$('#qupdMail').val(ui.item.billing_email);
						$('#cart-quote-address1').val(ui.item.billing_address1);
						$('#cart-quote-address2').val(ui.item.billing_address2);
						$('#cart-quote-country').val(ui.item.billing_country).change();
						$('#cart-quote-state').val(ui.item.billing_state);
						$('#cart-quote-city').val(ui.item.billing_city);
						$('#cart-quote-zip').val(ui.item.billing_zip);
						$('#cart-quote-phone').val(ui.item.billing_phone);
						if (ui.item.shipping_address != null){
							$('#same-data-for-shipping').removeAttr('checked').change();
							$('#shipping-firstname').val(ui.item.shipping_address.firstname);
							$('#shipping-lastname').val(ui.item.shipping_address.lastname);
							$('#shipping-company').val(ui.item.shipping_address.company);
							$('#shipping-email').val(ui.item.shipping_address.email);
							$('#shipping-address1').val(ui.item.shipping_address.address1);
							$('#shipping-address2').val(ui.item.shipping_address.address2);
							$('#shipping-country').val(ui.item.shipping_address.country).change();
							$('#shipping-state').val(ui.item.shipping_address.state);
							$('#shipping-city').val(ui.item.shipping_address.city);
							$('#shipping-zip').val(ui.item.shipping_address.zip);
							$('#shipping-phone').val(ui.item.shipping_address.phone);
						} else {
							if (!$('#same-data-for-shipping').attr('checked'))  $('#same-data-for-shipping').attr('checked', true).change();
							$('#shipping-data :input[name^="shipping-"]').val('')
						}
					} catch (exception) {
						if (window.console) {
							console.log(exception);
						}
					}
					$(this).blur();
					return false;
				}
		}).data( "autocomplete" )._renderItem = function( ul, item ) {
			return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append( "<a><b>Quote #"+item.id +':</b> '+ item.billing_name +', '+ item.billing_email+ "<br>" +'Has shipping address: <b>'+ (item.shipping_address != null ? 'yes' : 'no') + "</b></a>" )
				.appendTo( ul );
		};

		var ajaxCache = {}, lastXhr;
    });
</script>
<style type="text/css">
.ui-autocomplete{
	max-height: 300px;
	overflow-y: auto;
	overflow-x: hidden;
	padding-right: 20px;
}
</style>
<div id="seotoaster" class="shoppingeditquote">
	<div id="editquotewrapper">
		<div class="success" style="display: none;" id="ajaxmsg"></div>
		<input type="hidden" id="wsurl-hidden" value="<?php echo $this->websiteUrl; ?>"/>
		<input type="hidden" id="qid-hidden" value="<?php echo $this->cartId; ?>"/>
		
		<input type="hidden" id="quoteId-hidden" value="<?php echo $this->quoteDetails['quoteId']; ?>"/>
        
		<input type="hidden" id="current-sub-total" value="<?php echo $this->subTotal; ?>" />
        <input type="hidden" id="current-tax-total" value="<?php echo $this->itemsTotalTax; ?>" />
		
		<div id="sc-groupbrands" style="display: none;">
			<a id="closeeditquote" href="javascript:;" onclick="$(this).parent().hide();"><img src="<?php echo $this->websiteUrl; ?>system/images/bg-close.png" alt="close" border="0"/></a>
			<p class="lbl">{%Categories%}</p>
			<div id="sc-groups"></div>
			<p class="lbl">{%Brands%}</p>
			<div id="sc-brands" style="height: auto"></div>
			<p class="lbl">{%Products%}</p>
			<div id="sc-products"></div>
		</div>

		<div id="address-book" class="ui-widget clearfix">
			<div id="address-list-container" class="ui-widget-content">
				<div style="position: relative; display: inline;">
				<label for="address-list-search"><span class="ui-icon ui-icon-search" style="display:inline-block;">&nbsp;</span></label>
				<?php echo $this->formText('address-list-search', '{%Start typing id, name or email to search among addresses%}'); ?>
				<div id="address-list-status">
					<img style="display:none;" alt="...{%searching%}..." src="<?php echo $this->websiteUrl;?>system/images/ajax-loader.gif"/>
					<span></span>
				</div>
				</div>
			</div>
		</div>

		<div id="quoteedittophead">
            
            <div id="billingaddress"  class="column_3 infoform">
                <h3 class="ui-widget-header" style="margin: 5px 0;">{%Billing Address%}:</h3>
                <p><label>{%Client name%}:</label><input type="text" id="cart-quote-name" name="cart-quote-name" value="<?php echo $this->additionalUserData['name'];?>" /></p>
                <p><label>{%Company%}:</label><input type="text" name="cart-quote-company" id="cart-quote-company" value="<?php echo $this->additionalUserData['company'];?>"/></p>
                <p><label>{%E-mail%}:</label><input type="text" id="qupdMail" value="<?php echo $this->userMail;?>" /></p>
                <p><label>{%Address%} 1:</label><input type="text" name="cart-quote-address1" id="cart-quote-address1" value="<?php echo $this->additionalUserData['address1'];?>"/></p>
                <p><label>{%Address%} 2:</label><input type="text" name="cart-quote-address2" id="cart-quote-address2" value="<?php echo $this->additionalUserData['address2'];?>"/></p>
                <p><label>{%Country%}:</label>
                    <?php echo $this->formSelect('cart-quote-country', $this->additionalUserData['country'], null,  RCMS_Object_QuickConfig_QuickConfig::$worldCountries); ?>
                </p>
                <p><label>{%City%}:</label><input type="text" name="cart-quote-city" id="cart-quote-city" value="<?php echo $this->additionalUserData['city'];?>"/></p>
                <p><label>{%State%}:</label>
                    <select id="cart-quote-state" name="cart-quote-state">
                    </select>
                </p>
                <p><label>{%Zip%}:</label><input type="text" name="cart-quote-zip" id="cart-quote-zip" value="<?php echo $this->additionalUserData['zip'];?>"/></p>
                <p><label>{%Phone%}:</label><input type="text" name="cart-quote-phone" id="cart-quote-phone" value="<?php echo $this->additionalUserData['phone'];?>"/></p>
                <p style="padding-top: 10px"><label style="font-size:14px; float: none; padding-right: 10px">{%Use same data for shipping%}? <input type="checkbox" style="width:auto;" name="same-data-for-shipping" id="same-data-for-shipping" <?php echo (empty($this->shippingData) ? 'checked=true' : ' ');?>/></label>
            </div>

            <div id="center" class="column_3 dates">
                <p><label>{%Creation date%}:</label><input type="text" id="qupdDate" value="<?php echo date('d M Y', $this->quoteDetails['quoteDate']); ?>" /></p>
                <p><label>{%Valid until%}:</label><input type="text" id="qupdValidUntilDate" value="<?php echo date('d M Y', $this->quoteDetails['quoteValidUntil']); ?>" /></p>
            </div>

            <div id="shipping-data" class="column_3 infoform">
                <h3 class="ui-widget-header" style="margin: 5px 0;">{%Shipping Address%}:</h3>
                <p><label>{%First Name%}:<span>*</span></label><input type="text" name="shipping-firstname" id="shipping-firstname" value="<?php echo $this->shippingData['firstname'];?>" <?php echo (empty($this->shippingData) ? 'disabled=true' : '');?> ></p>
                <p><label>{%Last Name%}:</label><input type="text" name="shipping-lastname" id="shipping-lastname" value="<?php echo $this->shippingData['lastname'];?>" <?php echo (empty($this->shippingData) ? 'disabled=true' : '');?> ></p>
                <p><label>{%Company%}:</label><input type="text" name="shipping-company" id="shipping-company" value="<?php echo $this->shippingData['company'];?>" <?php echo (empty($this->shippingData) ? 'disabled=true' : '');?> ></p>
                <p><label>{%E-mail%}:</label> <input type="text" name="shipping-email" id="shipping-email" value="<?php echo $this->shippingData['email'];?>" <?php echo (empty($this->shippingData) ? 'disabled=true' : '');?> ></p>
                <p><label>{%Shipping Address%} 1:<span>*</span></label><input type="text" name="shipping-address1" id="shipping-address1" value="<?php echo $this->shippingData['address1'];?>" <?php echo (empty($this->shippingData) ? 'disabled=true' : '');?> ></p>
                <p><label>{%Shipping Address%} 2:</label><input type="text" name="shipping-address2" id="shipping-address2" value="<?php echo $this->shippingData['address2'];?>" <?php echo (empty($this->shippingData) ? 'disabled=true' : '');?> ></p>
                <p><label>{%Country%}:<span>*</span></label>
                    <?php echo $this->formSelect('shipping-country', null, empty($this->shippingData) ? array('disabled'=>true):null,  RCMS_Object_QuickConfig_QuickConfig::$worldCountries); ?>
                </p>
                <p><label>{%City%}:<span>*</span></label><input type="text" name="shipping-city" id="shipping-city" value="<?php echo $this->shippingData['city'];?>" <?php echo (empty($this->shippingData) ? 'disabled=true' : '');?> ></p>
                <p><label>{%State%}:</label>
                    <select id="shipping-state" name="shipping-state" <?php echo (empty($this->shippingData) ? 'disabled=true' : '');?> >
                    </select>
                </p>
                <p><label>{%ZIP Code%}:<span>*</span></label><input type="text" name="shipping-zip" id="shipping-zip"  value="<?php echo $this->shippingData['zip'];?>" <?php echo (empty($this->shippingData) ? 'disabled=true' : '');?> ></p>
                <p><label>{%Phone%}:</label><input type="text" name="shipping-phone" id="shipping-phone"  value="<?php echo $this->shippingData['phone'];?>" <?php echo (empty($this->shippingData) ? 'disabled=true' : '');?> ></p>
            </div>

			
		</div>
        <div style="clear:both; padding: 15px 0">
			<h1>
                {%Quote%} # <?php echo $this->quoteDetails['quoteId']; ?>
                <input type="text" id="qupdName" style="vertical-align: top" value="<?php echo $this->quoteDetails['quoteName'];?>" />
            </h1>
		</div>

		<div id="usercart-holder">
            <div id="usercart-legend">
				<div class="photo">{%Photo%}</div>
				<div class="name">{%Product%}</div>
				<div class="note">{%Note%}</div>
				<div class="qty">{%Qty%}</div>
                <div class="price">{%Price%} (<span style="font-size: 12px;"><?php echo $this->shoppingConfig['currency']; ?></span>)</div>
                <div class="fullprice">{%Total%} (<span style="font-size: 12px;"><?php echo $this->shoppingConfig['currency']; ?></span>)</div>
			</div>
			<div id="usercart">
				<?php if(!empty($this->cartData)): ?>
					<?php foreach ($this->cartData as $id => $cartItem): ?>
						<div class="usercart-item-product">
							<div class="photo"><img src="<?php echo $this->websiteUrl . $cartItem['photo']; ?>" width="50" height="50" alt="<?php echo $cartItem['name']; ?>"/></div>
							<div class="name">
								<?php echo $cartItem['name']; ?>
								<?php if(isset($cartItem['options'])): ?>
									<?php foreach($cartItem['options'] as $optName => $optVal): ?>
										<?php if($optVal != 'select' . $optName): echo $optName . ': ' . $optVal; endif; ?>
									<?php endforeach; ?>
								<?php endif; ?>
							</div>
                            <div class="note"><?php echo $this->formText('adminnote-'.$id, $cartItem['note'], array('class'=>'adminnote')); ?></div>
                            <div class="qty">
                                <?php echo $this->formText('inptoupdcnt-'.$id, $cartItem['count'], array('class'=>'itqty')) ;?>
                            </div>
							<div class="price">
                                <?php echo $this->formText('inptoupd-'.$id, $cartItem['price'], array('class'=>'itprice')); ?>
                                <span style="font-size: 12px;">&nbsp;<?php echo $this->shoppingConfig['currency']; ?></span>
                            </div>
							<div class="fullprice">
                                <?php echo $this->formText('inpfullprice-'.$id, $cartItem['count']*$cartItem['price'], array('class'=>'itfullprice', 'readonly'=>true)); ?>
                                <span style="font-size: 12px;">&nbsp;<?php echo $this->shoppingConfig['currency']; ?></span>
                            </div>
						</div>
					<?php endforeach; ?>
				<?php endif; ?>
			</div>
			<div id="statusline">
				<div id="total">
                    <div class="line">
                        <span>{%Sub-total%}:</span>
                        <span class="currency"><?php echo $this->shoppingConfig['currency']; ?></span>
                        <span class="cnt"><?php echo number_format($this->subTotal,2,'.',''); ?></span>
                    </div>
					<div class="line">
                        <span>{%Tax%}:</span>
                        <span class="currency"><?php echo $this->shoppingConfig['currency']; ?></span>
                        <span class="cnt"><?php echo number_format($this->itemsTotalTax, 2, '.', ''); ?></span>
                    </div>
                    <?php if ($this->quoteDetails['quoteShipping'] !== false) :?>
                    <div class="line">
                        <span>{%Shipping%}:</span>
                        <span class="currency"><?php echo $this->shoppingConfig['currency']; ?></span>
                        <span class="cnt">
                            <?php echo $this->formText('shipping',number_format($this->quoteDetails['quoteShipping'],2,'.',''),array('class'=>'recountTotal','maxlenght'=>'10')); ?>
                        </span>
                    </div>
					<?php endif; ?>
					<div class="line">
                        <span>{%Discount%}:</span>
                        <span class="currency"><?php echo $this->shoppingConfig['currency']; ?></span>
                        <span class="cnt">
                            <?php echo $this->formText('discount',$this->quoteDiscount?$this->quoteDiscount:'0',array('class'=>'recountTotal','maxlenght'=>'10','style'=>'width:80px')); ?>
                        </span>
						<span class="cnt">
							<?php echo $this->formSelect('discount-tax-rate', $this->quoteDiscountTaxRate, array('style'=>'width:80px'), $this->taxLabels) ; ?>
						</span>
                    </div>
					<hr size="2"/>
					<div class="line" style="color:#555;">
						<span>{%Grand Total%}:</span>
						<span class="currency"> <?php echo $this->shoppingConfig['currency']; ?></span>
						<span class="cnt" id="grand-total">
							<?php echo number_format(($this->subTotal+$this->itemsTotalTax+$this->quoteDetails['quoteShipping']-$this->quoteDiscount),2,'.',''); ?>
						</span>
					</div>
					<div class="line" style="color:#999; font-size: 18px;">
                        <span>{%Inc. Tax%} {%after discount%}:</span>
                        <span class="currency"><?php echo $this->shoppingConfig['currency']; ?></span>
                        <span class="cnt" id="current-tax-amount"><?php echo number_format($this->itemsTotalTax - $this->taxDiscount, 2, '.', ''); ?></span>
                    </div>
				</div>
				<div style="float: right; margin: 64px 15px 0 0; border-bottom: 1px dashed rgb(238, 238, 238); padding-bottom: 5px;">
					<p>
						<span style="font-size: 22px; font-weight: bold">{%Shipping method%}:</span>
						<span>
							<?php echo $this->formText('shipping-method',$this->shippingMethod?$this->shippingMethod:'',array()); ?>
						</span>
					</p>
				</div>
                <div id="buttons" style="clear:both;">
                    <button class="formsubmit" id="addprod" onclick="addProductForQuote();">{%Add product%}</button>
					<button class="formsubmit" id="updCart">{%Update cart%}</button>
				</div>
			</div>
		</div>
		<div id="msgholder">
			<p><input type="text" style="width:800px" name="quote-disclaimer" id="quote-disclaimer" value="<?php echo ($this->quoteDetails['quoteDisclaimer']) ? $this->quoteDetails['quoteDisclaimer'] : '{%Disclaimer%}:' ;?>" /></p>
			<div id="mailuserwin">
                <div class="lbl">{%Client email message%} <span onclick="$('.infovariables').slideToggle();">{%help%}</span></div>
				<div class="infovariables" onclick="$(this).hide();">
                    <p>{%Note: you can set this template in &ldquo;Shopping&rdquo; => &ldquo;Templates&rdquo; menu%}</p>
					<div>
						<p>{$name} - {%Client name%}</p>
						<p>{$date} - {%Current date%}</p>
						<p>{$quote_url} - {%Quote preview url%}</p>
						<p>{$logged_user} - {%Nickname and email of logged user%}</p>
					</div>
                </div>
				<textarea id="mailusertext" cols="22" rows="6"><?php echo $this->quoteDetails['mailToUser']; ?></textarea>
			</div>
			<div id="internalmsgwin">
				<div class="lbl">{%Internal Notes%}:</div>
				<textarea id="intmsgtext" cols="22" rows="6"><?php echo trim($this->quoteDetails['quoteIntMsg']); ?></textarea>
			</div>
		</div>
		<div id="bottomline">
            <?php if($this->quoteDetails['hasPreview']): ?>
            <div>
<!--                <a target="_blank" href="<?php echo $this->websiteUrl; ?>sys/backend_quote/preview/qid/<?php echo $this->quoteDetails['quoteId'] .'.'. md5($this->quoteDetails['quoteId']) . '.' . $this->quoteDetails['quoteId']; ?>">{%Quote preview%}</a>-->
                <button id="previewQuote" class="formsubmit" onclick="prew = window.open('<?php echo $this->websiteUrl."sys/backend_quote/preview/qid/".$this->quoteDetails["quoteId"] .".". md5($this->quoteDetails["quoteId"]).".".$this->quoteDetails["quoteId"]; ?>', '_blank');" >{%Quote Preview%}</button>
            </div>
            <?php endif;?>
			
            <div>
                <button id="saveQuote" class="formsubmit" onclick="generateQuote(false);">{%Save quote%}</button>
            </div>
            <div>
                <button id="generateQuote" class="formsubmit" onclick="generateQuote(true);">{%Save &amp; send quote%}</button>
            </div>
            <div>
                <span style="white-space: nowrap">{%Last edited by%}:&nbsp;<?php echo $this->lastEditedBy;?></span>
            </div>
        </div>
	</div>
</div>